import React, { useState, useEffect } from 'react';
import {
  Card,
  Button,
  Input,
  Form,
  Icon,
  DatePicker,
  message,
  Row,
  Col,
  Upload,
  Tooltip,
} from 'antd';
import { connect } from 'dva';
import styles from '../index.less';
import router from 'umi/router';
import Link from 'umi/link';
import getCursortPosition from './getCursortPosition';
import setCaretPosition from './setCaretPosition';
import moment from 'moment';
import { userId } from '@/constant';
const id = window.sessionStorage.getItem(userId);
const creator = (type, payload) => ({ type, payload });
const { TextArea } = Input;
const format = 'YYYY-MM-DD';
const NewPerson = props => {
  const { form, dispatch, person } = props;
  const { previewData, allPerson } = person;
  const { getFieldDecorator } = form;

  //获取所有人物列表
  useEffect(() => {
    dispatch(creator('person/getPerson'));
  }, [dispatch]);
  //光标定位的位置
  const [index, setIndex] = useState(0);
  const [lifeTimeData, setLifeTimeData] = useState([
    {
      title: '童年',
      desc: '童年',
    },
    {
      title: '小学',
      desc: '小学',
    },
    {
      title: '初中',
      desc: '初中',
    },
  ]);
  //人物概述
  const [overview, setOverview] = useState([
    { desc: '请简要概述该人物的主要内容，建议100-300字。（必填）' },
  ]);
  //人物概述原始数据
  const [overviewOrigin, setOverviewOrigin] = useState([{ desc: '' }]);
  //loading
  const [loading, setLoading] = useState(false);
  //imageUrl
  const [imageUrl, setImageUrl] = useState('');
  //确认显示隐藏
  const [btn, setBtn] = useState(false);
  //详情显示隐藏
  const [detail,setDetail]=useState(false)
  //输入框校验是否通过
  const [pass,setPass]=useState(false)
  //输入框是否禁用
  const [input,setInput]=useState(false)
  useEffect(() => {
    //预览返回时，填写信息恢复
    if (Object.keys(previewData).length) {
      form.setFieldsValue({
        name: previewData.name,
        chineseName: previewData.chineseName,
        birthDate: previewData.birthDate ? moment(previewData.birthDate) : null,
        englishName: previewData.englishName,
        deathDate: previewData.deathDate ? moment(previewData.deathDate) : null,
        alias: previewData,
        alias: previewData.alias,
        college: previewData.college,
        nationality: previewData.nationality,
        career: previewData.career,
        nation: previewData.nation,
        represent: previewData.represent,
        birthPlace: previewData.birthPlace,
        achievement: previewData.achievement,
        evaluation: previewData.evaluation,
      });
      setOverview([...previewData.overview]);
      setLifeTimeData([...previewData.lifetime]);
      setImageUrl(previewData.imageUrl);
      setBtn(false);//确认按钮隐藏
      setPass(true);//验证通过
      setDetail(true)//详情显示
      setInput(true)//输入框禁用
    }
  }, [form, previewData]);

  const [basicInfo, setBasicInfo] = useState([
    {
      label: '中文名',
      key: 'chineseName',
      placeholder: '填写中文名或中文译名',
    },
    {
      label: '出生日期',
      key: 'birthDate',
      placeholder: '',
    },
    {
      label: '英文名',
      key: 'englishName',
      placeholder: '',
    },
    {
      label: '逝世日期',
      key: 'deathDate',
      placeholder: '',
    },
    {
      label: '别名',
      key: 'alias',
      placeholder: '如有多项请以#分割',
    },
    {
      label: '毕业院校',
      key: 'college',
      placeholder: '如有多项请以#分割',
    },
    {
      label: '国籍',
      key: 'nationality',
      placeholder: '请选择或搜索国籍',
    },
    {
      label: '职业',
      key: 'career',
      placeholder: '',
    },
    {
      label: '民族',
      key: 'nation',
      placeholder: '',
    },
    {
      label: '代表作品',
      key: 'represent',
      placeholder: '如有多项请以#分割',
    },
    {
      label: '出生地',
      key: 'birthPlace',
      placeholder: '',
    },
    {
      label: '主要成就',
      key: 'achievement',
      placeholder: '如有多项请以#分割',
    },
  ]);

  const plusOrMinus = (type, index) => {
    if (type === 'plus') {
      let obj = {
        title: '标题',
        desc: '请输入内容',
      };
      lifeTimeData.splice(index + 1, 1, obj);
    } else if (type === 'minus') {
      lifeTimeData.splice(index, 1);
    }
    setLifeTimeData([...lifeTimeData]);
  };
  const titleChange = (index, e) => {
    lifeTimeData[index]['title'] = e.target.value;
    setLifeTimeData([...lifeTimeData]);
  };
  const TextAreaChange = (index, e) => {
    lifeTimeData[index]['desc'] = e.target.value;
    setLifeTimeData([...lifeTimeData]);
  };
  //预览或提交时
  const submitHandle = type => {
    form.validateFields((err, fields) => {
      console.log(fields);
      fields.lifetime = lifeTimeData;
      fields.overview = overviewOrigin;
      fields.imageUrl = imageUrl;
      fields.birthDate = moment(fields.birthDate).format(format);
      fields.deathDate = moment(fields.deathDate).format(format);
      console.log(fields.alias);
      fields.alias =
        fields.alias && fields.alias.indexOf('#') !== -1 ? fields.alias.split('#') : [fields.alias];
      fields.college =
        fields.college && fields.college.indexOf('#') !== -1
          ? fields.college.split('#')
          : [fields.college];
      fields.represent =
        fields.represent && fields.represent.indexOf('#') !== -1
          ? fields.represent.split('#')
          : [fields.represent];
      fields.achievement =
        fields.achievement && fields.achievement.indexOf('#') !== -1
          ? fields.achievement.split('#')
          : [fields.achievement];
      if (type === 0) {
        //预览
        dispatch(creator('person/savePreview', fields));
        router.push('/outer-world/encyclopedias/person/preview');
      } else if (type === 1) {
        fields.createBy=id;
        fields.createTime=moment().format(format);
        //提交
        dispatch(creator('person/updatePerson', fields)).then(res=>{
          if(res.httpStatus===200){
            message.success('新增成功')
            router.push('/outer-world/encyclopedias');
          }else{
            message.fail('新增出错')
          }
        })
      }
    });
  };
  //按下enter
  const onKeyDown = (i, e) => {
    //enter键
    if (e.keyCode === 13) {
      e.preventDefault();
      let pArr = document.getElementsByClassName('overview');
      let obj = { desc: '' };
      overviewOrigin.splice(index + 1, 0, obj);
      overview.splice(index + 1, 0, obj);
      setOverview([...overview]);
      setIndex(index => index + 1);
    }
    //backSpace键
    if (e.keyCode === 8) {
      let pArr = document.getElementsByClassName('overview');
      if (!pArr[index].innerHTML && index !== 0) {
        //无值且不是第一个p标签时
        overview.splice(index, 1); //删除该p标签
        overviewOrigin.splice(index, 1); //删除该p标签
        setIndex(index => index - 1);
      }
    }
  };
  //文本变化时
  const inputHandle = e => {
    let pArr = document.getElementsByClassName('overview');
    let pos = pArr[index].innerHTML.length;
    overviewOrigin[index]['desc'] = pArr[index].innerHTML;
  };
  useEffect(() => {
    let pArr = document.getElementsByClassName('overview');
    let pos = pArr[index].innerHTML.length;
    setCaretPosition(pArr[index], pos);
  }, [index]);
  const onFocus = (i, e) => {
    let pArr = document.getElementsByClassName('overview');
    // if(pArr[index].innerHTML.indexOf('请简要概述')!==-1){
    //   overview[index]['desc']=''
    //   setOverview([...overview])
    // }
    setIndex(index => (index = i));
  };

  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传jpg或png类型的图片！');
      return false;
    }
    return new Promise((resolve, reject) => {
      let _URL = window.URL || window.webkitURL;
      let img = new Image();
      img.onload = function() {
        var ww = img.width;
        var hh = img.height;
        let valid = ww < 320 || hh < 320;
        console.log(valid);
        !valid ? resolve() : reject();
      };
      img.src = _URL.createObjectURL(file);
    }).then(
      () => {
        return file;
      },
      () => {
        message.error(file.name + '图片尺寸不符合要求，请修改后重新上传！');
        return Promise.reject();
      },
    );
  }

  const basicInfoContent = (item, index) => {
    switch (index) {
      case 1:
        return <DatePicker className={styles.inputWidth} placeholder={item.placeholder} />;
        break;
      case 3:
        return <DatePicker className={styles.inputWidth} placeholder={item.placeholder} />;
        break;
      default:
        return <Input className={styles.inputWidth} placeholder={item.placeholder} />;
    }
  };
  //名称确认
  const confirmName = () => {
    let name = form.getFieldValue('name');
    const id = window.sessionStorage.getItem(userId);
    if (!name) {
      message.warn('人物名称不可为空!');
      return;
    }
    let obj = {
      createBy: id,
      name,
    };
    dispatch(creator('person/writePerson', obj)).then(res=>{
      if(res.httpStatus===200){
        setBtn(false);//确认按钮隐藏
        setDetail(true)//详情显示
        setInput(true)//输入框禁用
      }
    })
  };
  const handleChange = info => {
    if (info.file.status === 'uploading') {
      // this.setState({ loading: true });
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imgUrl =>
        // setLoading(false),
        setImageUrl(imgUrl),
      );
    }
  };
  const inputChange = e => {
    if (e.target.value) {
      let flag = allPerson.every(item => item.name !== e.target.value);
      if (flag) {
        //数据库无此人物
        setPass(true)
        setBtn(true);
      } else {
        setBtn(false);
      }
    }
  };
  useEffect(() => {
    // console.log(imageUrl);
  }, [imageUrl]);

  const basicTitle = (
    <>
      <span>基本信息</span>
      <span style={{ fontSize: 12 }}>（注：未填写内容的信息项将不会显示在词条页上）</span>
    </>
  );

  const formItemLayout = {
    labelCol: {
      xs: { span: 12 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 12 },
      sm: { span: 17 },
    },
  };
  const uploadButton = (
    <span style={{ display: 'inline-block', marginTop: 60, fontSize: 12, color: '#ccc' }}>
      <Icon type="plus" />
      <br />
      <span>图片格式为png/jpg</span>
      <span>宽高像素不低于320px*320px</span>
    </span>
  );
  return (
    <div style={{ margin: 20 }}>
      <div className={styles.top_button}>
        <Button style={{ marginRight: 10 }} shape="round" onClick={submitHandle.bind(this, 0)}>
          {/* <Link to='/outer-world/encyclopedias/person/preview' target='_blank'> */}
          预览
          {/* </Link> */}
        </Button>

        <Button
          shape="round"
          style={{ marginRight: 60 }}
          type="primary"
          onClick={submitHandle.bind(this, 1)}
        >
          提交
        </Button>
      </div>
      <Form style={{ margin: '0 auto', width: 850 }}>
        <Form.Item>
          {getFieldDecorator('name', {
            // rules: [
            //   {
            //     required: true,
            //     message: '请输入该人物名称',
            //   },
            // ],
          })(
            <Input
              disabled={input?true:false}
              placeholder="请输入该人物名称"
              onInput={inputChange}
              suffix={
                <Tooltip>
                  {!pass ? (
                    <Icon type="close-circle" style={{ color: 'rgb(255,0,0)' }} />
                  ) : (
                    <Icon type="check-circle" style={{ color: 'rgb(0,255,0)' }} />
                  )}
                </Tooltip>
              }
            />,
          )}
        </Form.Item>
        <Form.Item style={{ display: !btn ? 'none' : 'inline-block', width: '100%' }}>
          <Button type="primary" style={{ width: '100%' }} onClick={confirmName}>
            确认
          </Button>
        </Form.Item>
        <div style={{ display: !detail ? 'none' : 'block' }}>
          <Form.Item>
            <Card title="人物概述" style={{ width: 850 }}>
              <Row>
                <Col span={18} style={{ minHeight: '200px' }}>
                  {overview.map((item, index) => (
                    <p
                      key={index}
                      suppressContentEditableWarning
                      contentEditable="true"
                      className="overview"
                      onInput={inputHandle}
                      onFocus={onFocus.bind(this, index)}
                      onKeyDown={onKeyDown.bind(this, index)}
                    >
                      {item.desc}
                    </p>
                  ))}
                </Col>
                <Col span={6} style={{ width: '180px', height: '180px' }}>
                  <Upload
                    style={{ display: 'inline-block', height: '180px', width: '180px' }}
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="api/person/uploadAvatar"
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                    data={{ name:form.getFieldValue('name'),createBy:id }}
                    // headers={{'content-type':'application/json;charset=utf-8'}}
                  >
                    {imageUrl ? (
                      <img
                        src={imageUrl}
                        alt="avatar"
                        style={{ width: '100%', width: '164px', height: '164px' }}
                      />
                    ) : (
                      uploadButton
                    )}
                    {/* {uploadButton} */}
                  </Upload>
                </Col>
              </Row>
            </Card>
          </Form.Item>
          <Form.Item>
            <Card title={basicTitle} style={{ width: 850 }}>
              {basicInfo.map((item, index) => (
                <Form.Item
                  key={item.label}
                  label={item.label}
                  labelAlign="right"
                  {...formItemLayout}
                  className={
                    index % 2 !== 0
                      ? `${styles.formItemLayout}`
                      : `${styles.formItemLayout} ${styles.inputMarginRight}`
                  }
                >
                  {getFieldDecorator(`${item.key}`, {})(basicInfoContent(item, index))}
                </Form.Item>
              ))}
            </Card>
          </Form.Item>
          <Form.Item>
            <Card title="人物生平" style={{ width: 850 }}>
              {lifeTimeData.map((item, index) => (
                <Card
                  className={styles.margin_top}
                  key={index}
                  type="inner"
                  title={
                    <Input
                      value={item.title}
                      style={{ width: 300 }}
                      className={styles.input_no_border}
                      onChange={titleChange.bind(this, index)}
                    />
                  }
                  extra={
                    <>
                      <a>
                        <Icon
                          type="plus-circle"
                          style={{ marginRight: 10 }}
                          onClick={plusOrMinus.bind(this, 'plus', index)}
                        />
                      </a>
                      <a>
                        <Icon
                          type="minus-circle"
                          onClick={plusOrMinus.bind(this, 'minus', index)}
                        />
                      </a>
                    </>
                  }
                >
                  <TextArea
                    rows={5}
                    value={item.desc}
                    onChange={TextAreaChange.bind(this, index)}
                  />
                </Card>
              ))}
            </Card>
          </Form.Item>
          <Form.Item>
            <Card title="社会评价">{getFieldDecorator('evaluation')(<TextArea rows={5} />)}</Card>,
          </Form.Item>
        </div>
      </Form>
    </div>
  );
};

const WrappedNewPerson = Form.create()(NewPerson);

export default connect(({ person }) => ({ person }))(WrappedNewPerson);
